package com.example.cdctest.managecontroller;

import com.example.cdctest.util.JSONResult;
import com.example.cdctest.util.TimestampEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.security.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestControllerAdvice
public class CommonControllerAdvice {
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
        binder.registerCustomEditor(Timestamp.class,new TimestampEditor("yyyy-MM-dd"));
    }

    @ExceptionHandler(Exception.class)
    public Object processException(Exception e, HttpServletRequest request)
    {
        if(isAjax(request)) {
            return JSONResult.errorMsg(e.getMessage());
        }
        else
        {
            String path=request.getHeader("referer");
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("path",path);
            modelAndView.addObject("exception",e);
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }

    public Boolean isAjax(HttpServletRequest request)
    {
        return "XMLHttpRequest".equals(request.getHeader("X-Request-With"));
    }
}
